/**
 * Used for test.
 * @ignore
 */
createCatStore = function(n){
    var data = [];
    for (var i = 1; i<n; i++)
        data.push({
        	id: i,
        	catName: 'Cat' + i
        });
    
    return new Ext.data.Store({
        model: 'NG.models.Category',
        sorters: 'catName',
        data: data
    });
};

/**
 * @class NG.views.CategoryList
 * @extends NG.util.List
 * This panel is used for listing categories.
 * This component is registered as 'netgis-categorylist' name.
 */
NG.views.CategoryList = Ext.extend(NG.util.List, {
	deferEmptyText:true,
	
	/**
	 * Default values is 'Kategori Bulunamadı'.
	 * @type String
	 */
	emptyText: 'Kategori Bulunamadı',
	loadingText: 'Kategori Yükleniyor',	
	scroll: 'vertical',
	singleSelect: true,
	minHeight: 300,
	height: 300,
	
	/**
	 * Unused.
	 * @type NG.views.MapView
	 * @ignore
	 */
    map: null,
    
    /**
     * Which workspace's categories are listed.
     * @type NG.models.Workspace
     */
    workspace:null,
    
    initComponent: function(){
    	var ws = this.workspace;
        this.itemTpl = new Ext.XTemplate(
            '<tpl if="visibility == true">', 
                '<img width="16" src="img/check-round-green.png">', 
            '</tpl>', 
            '<tpl if="visibility == false">', 
                '<img width="16" src="img/check-round-grey.png">', 
            '</tpl>', 
            '&nbsp;<img width="16" src="' + ws.getIconUrl() + '{iconType}">', 
            '<span class="gx-layer-item">{catName}-{catID}</span>',
            '<tpl if="this.isValid(catID) == true">',
	            '<tpl if="selected == false">', 
	            	'<div style="float: right; padding-right: 10px;" class="compose x-icon-mask">' + '<input class="x-button x-button-decline" type="button" value="Seç">' + '</div>',
		        '</tpl>', 
		        '<tpl if="selected == true">', 
		        	'<span style="float: right; padding-right: 10px;">' + '<input class="x-button x-button-confirm" type="button" value="-->">' + '</span>',
		        '</tpl>',            
		    '</tpl>',
		    {
            	compiled: true,
    		    isValid: function (id){
    		    	return !Ext.isEmpty(id);
    		    }            	
		    }
        );
        NG.views.CategoryList.superclass.initComponent.call(this);
    },

    /**
     * List consists of NG.models.Category objects.
     * @param {NG.util.List} list Category list
     */
    loadCategories: function (list){
    	list.el.mask(L_LOADING);
    	
    	function loadCategories (categories){
    		list.store.loadData(categories);
			list.applyButton.enable();
			list.el.unmask();
    	}
    	
    	function doGetCategories (getCategoriesCommand, sessionID){
			if (NGCategoryCache.containsKey(getCategoriesCommand.getCacheKey())) {
				var categories = NGCategoryCache.get(getCategoriesCommand.getCacheKey());
				loadCategories(categories);
			} else {
	    		NGServiceRequester.executeCommand(getCategoriesCommand, sessionID, {
	            	requestFinished: function (response) {
	            		NGLogger.info("Finish GetCategoriesCommand: ");
	            		var getCategoriesResponse = new NG.response.GetCategories({
	            			xmlData: response
	            		});
	            		list.store.removeAll();
	            		var categories = getCategoriesResponse.getCategories();
	            		loadCategories (categories);
						//Add into NGCategoryCache
	            		NGCategoryCache.add(getCategoriesCommand.getCacheKey(), categories);
	            	},
	            	requestFail: function (response) {
						list.store.add({
							catName: 'İstek Başarısız'
						});
						list.applyButton.disable();
						list.el.unmask();	            		
	            	}
	    		});			
			}    		
    	}
    	
		var getCategoriesCommand = new NG.command.GetCategories({
			workspaceName: this.workspace.getName(),
        	runXmlUrl: this.workspace.getRunXmlUrl()
		});		    	
		
    	var ws = this.workspace;
		var session = NGServiceRequester.isAlreadyLoggedIn(ws.getUsername(), ws.getLoginUrl());
		if (session) {
			doGetCategories(getCategoriesCommand, session.sessionID);
		} else {
			NGServiceRequester.login(ws.getUsername(), ws.getPassword(), ws.getLoginUrl(), {
				loginSuccess: function(sessionID) {
					doGetCategories(getCategoriesCommand, sessionID);
				},
				loginFail: function(response) {
					list.store.add({
						catID: null,
						catName: MSG_COULD_NOT_CONNECT
					});
					list.applyButton.disable();
					list.el.unmask();
				}
			});
		}	
    },
    
    /**
     * @param {boolean} selected If true selected categories else unselected categories
     * @return {String} selected Categories' id separated by ;
     */
    getSelectedCategories: function (selected){
    	selected = Ext.isEmpty(selected) ? true : selected;
    	var result = "";
    	for ( var i = 0; i < this.getStore().getCount(); i++) {
            var record = this.getStore().getAt(i);
            if (selected ? record.get("visibility") : !record.get("visibility"))
            	result += record.getCatID() + NG_COF_SEPARATOR;
		}
    	return result.removeLastChar();
    },
    
    /**
     * 
     * @returns {String} unselected Categories' id separated by ;
     */
    getUnSelectedCategories: function (){
    	return this.getSelectedCategories(false);
    },
    
    listeners: {
        itemtap: function(dataview, index, item, e){
            var record = dataview.getStore().getAt(index);
        	if (e.target.type === "button") {
            	e.preventDefault();
        		dataview.deselectAll();
        		
            	//Firstly, Make all rows unselected
            	for ( var i = 0; i < dataview.getStore().getCount(); i++) {
            		var tmpRecord = dataview.getStore().getAt(i); 
            		if (record.equalsTo(tmpRecord))
            			continue;
            		tmpRecord.set("selected", false);					
    			}
                record.set("selected", !record.get("selected"));
                
                if (record.get("selected") === true) {
                	app.views.mapView.setSelectedCategory(record);            	
                } else {
                	app.views.mapView.setSelectedCategory(null);
                }
                
        		return;
        	}
            record.set("visibility", !record.get("visibility"));
        },    	
    	afterrender : function (dataview) {
    		this.loadCategories(dataview);
    	} 
    }
    
});

/**
 * Creates an overlay panel for listing categories.
 * 
 * @param {Object} config Includes mapView, workspace
 * @return {Ext.Panel} category list panel
 */
NG.views.CategorListOverlay = function (config) {
	config = config || {};
	var applyButton = new Ext.Button({
		ui: 'confirm',
		text: L_APPLY,
		disabled: true,
		handler: function(){
			var unSelectedCategories = Ext.getCmp('netgis-categorylist-id').getUnSelectedCategories();
			overlay.hide();
			//render map with new categories
			config.mapView.renderWorkspaceWithOffCategories(unSelectedCategories);
		}
	});
    var overlay = new Ext.Panel({
		fullscreen: Ext.is.Phone,
        floating: true,
        modal: true,
        centered: true,
        hideOnMaskTap: true,
	    width: Ext.is.Phone ? 260 : 400,
	    //height: Ext.is.Phone ? 220 : 400,
	    scroll: 'vertical',
    	dockedItems: [{
			//dock : 'bottom',
			xtype: 'toolbar',
			ui   : 'light',
			title: L_WS_LAYERS,
			items: [{
					iconCls: 'delete',
					iconMask: true,
					ui: 'plain',
					handler: function (){
						overlay.hide();
					}
				},
				{xtype:'spacer'},
				applyButton
			]
    	}],  //!dockedItems          	
        items: [{
        	id: 'netgis-categorylist-id',
        	xtype: 'netgis-categorylist',
        	applyButton: applyButton, 
        	workspace: config.workspace,
        	store: new Ext.data.Store({
        	    model: 'NG.models.Category',
        	    data : []
        	})
        }]
    });
	
	return overlay;
};

/**
 * @ignore
 */
Ext.reg('netgis-categorylist', NG.views.CategoryList);
